# This file is part of the Net::Tube module.
#
# Net::Tube is Free Software; you can use, redistribute it and/or
# modify it under the terms of either:
#
# a) the GNU General Public License as published by the Free Software
#    Foundation, either version 2, or (at your opinion) any later
#    version, or
#
# b) the "Artistic License" which comes with Perl.
#
use strict;
use warnings;
use Test::Simple tests => 3;

use Net::Tube;
use Net::Tube::Loader::File;
use Net::Tube::Filter::SemanticMerge;
use Net::Tube::Filter::Sort::Number;


sub test_new {
    my $x = Net::Tube::Filter::Sort::Number->new();
    unless ( defined $x && ref $x ) {
        print "#object not created \n";
        return 0;
    }
    unless ( $x->isa("Net::Tube::Filter::Sort::Number") ) {
        print "# wrong object type created\n";
        return 0;
    }
    return 1;
}

ok( test_new(), "test new" );


sub test_sort {
    my $m = Net::Tube::Machine->new();
    my $c =
      Net::Tube::Loader::File->new(
        { loadSource => ['tdata/simple_4.xml'] } );
    my $sm =
      Net::Tube::Filter::Sort::Number->new(
        { 'sort-element' => 'B/a', 'ref-element' => 'y' } );

    my $data = $m->execute( [ $c, $sm ] );

    unless ( defined $data && length $data ) {
        print "# data is missing \n";
        return 0;
    }

    my $doc = XML::LibXML->new()->parse_string($data);
    my $v   = $doc->findvalue('/B/a/x');
    unless ( defined $v && length $v ) {
        print "# data in XML is missing\n";
        return 0;
    }

    unless ( $v eq 'abdxz' ) {
        print "# wrong data has been found: $v\n";
        return 0;
    }

    return 1;
}

ok( test_sort(), "normal sort" );

sub test_sort_desc {
    my $m = Net::Tube::Machine->new();
    my $c =
      Net::Tube::Loader::File->new(
        { loadSource => ['tdata/simple_4.xml'] } );
    my $sm = Net::Tube::Filter::Sort::Number->new(
        {
            'sort-element' => 'B/a',
            'ref-element'  => 'y',
            'direction'    => 'descending'
        }
    );    

    my $data = $m->execute( [ $c, $sm ] );

    unless ( defined $data && length $data ) {
        print "# data is missing \n";
        return 0;
    }

    my $doc = XML::LibXML->new()->parse_string($data);
    my $v   = $doc->findvalue('/B/a/x');
    unless ( defined $v && length $v ) {
        print "# data in XML is missing\n";
        return 0;
    }

    unless ( $v eq 'zxdba' ) {
        print "# wrong data has been found: $v\n";
        return 0;
    }

    return 1;
}

ok( test_sort_desc(), "normal sort descending" );
